import path from "path"
import express from "express"
import multer from "multer"

const router = express.Router()

/* 创建磁盘存储引擎 */
const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, './uploads/')
  },
  filename(req, file, cb) {
    cb(null, `${file.originalname.split(".")[0]}${Date.now()}${path.extname(file.originalname)}`)
  }
})

/* 验证文件类型 */
const checkFileType = (file, cb) => {
  /* 允许类型 */
  const filterTypes = /jpg|jpeg|png/i
  /* 判断扩展名 */
  const extname = filterTypes.test(path.extname(file.originalname))
  
  if(extname) {
    return cb(null, true)
  } else {
    return cb('仅限图片格式')
  }
}

const upload = multer({
  storage, 
  fileFilter: function(req, file, cb) {
    checkFileType(file, cb)
  }
})

/* 实现路由 */
router.post('/product-cover', upload.single('image'), (req,res) => {
  if(req.file) {
    res.json({
      success:true,
      msg: '上传成功',
      data: `http://localhost:5000/${req.file.path}`
    })
  } else {
    res.json({
      success:false,
      msg: '上传失败',
      data: null
    })
  }
})

/* 上传路由 */


export default router